//go:build linux
// +build linux

package internal

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
	"reflect"
	"strings"
)

func GetSocketUid(port int64, network int8) (uid string, err error) {
	var file *os.File
	portHex := fmt.Sprintf("%04X", port)

	fmt.Println(reflect.TypeOf(portHex))
	file, err = os.Open("/proc/net/tcp")
	if err != nil {
		return "", err
	}
	defer file.Close()

	uid = search(file, portHex)

	if len(uid) == 0 {
		file, err = os.Open("/proc/net/tcp6")
		if err != nil {
			return "", err
		}
		defer file.Close()

		uid = search(file, portHex)

		if len(uid) == 0 {
			return "", errors.New("get SocketId fail")
		}
		return
	}
	return
}

func search(file *os.File, portHex string) (uid string) {

	if file == nil || len(portHex) == 0 {
		return
	}

	br := bufio.NewReader(file)

	for {
		a, _, c := br.ReadLine()
		if c == io.EOF {
			break
		}
		Info := strings.Fields(string(a))

		// Info不同位置代表不同
		remPort := strings.Split(Info[1], ":")
		if len(remPort) == 2 {
			if remPort[1] == portHex {
				uid = Info[7]
				//SocketId = Info[9]
				return
			}
		}
	}

	return ""
}
